const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const session = require('express-session')
const bcrypt = require('bcryptjs') // 添加密码哈希

const app = express()

// 中间件
app.use(cors({
  origin: 'http://localhost:8080', // 前端地址
  credentials: true
}))
app.use(bodyParser.json())
app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { 
    secure: false, // 生产环境设为true (HTTPS)
    maxAge: 24 * 60 * 60 * 1000 // 24小时
  }
}))

// 模拟用户数据库 (添加密码哈希)
const users = [
  {
    id: 1,
    username: 'user1',
    password: bcrypt.hashSync('password1', 10), // 哈希密码
    email: 'user1@example.com',
    avatar: 'https://via.placeholder.com/150',
    createdAt: new Date()
  },
  {
    id: 2,
    username: 'user2',
    password: bcrypt.hashSync('password2', 10),
    email: 'user2@example.com',
    avatar: 'https://via.placeholder.com/150',
    createdAt: new Date()
  }
]

// 注册接口 (新增)
app.post('/api/register', async (req, res) => {
  const { username, password, email } = req.body
  
  // 简单验证
  if (!username || !password || !email) {
    return res.status(400).json({ 
      success: false,
      message: '请提供用户名、密码和邮箱'
    })
  }
  
  // 检查用户是否已存在
  if (users.some(u => u.username === username)) {
    return res.status(400).json({ 
      success: false,
      message: '用户名已存在'
    })
  }
  
  try {
    const newUser = {
      id: users.length + 1,
      username,
      password: bcrypt.hashSync(password, 10),
      email,
      avatar: 'https://via.placeholder.com/150',
      createdAt: new Date()
    }
    
    users.push(newUser)
    
    res.status(201).json({ 
      success: true,
      data: {
        id: newUser.id,
        username: newUser.username,
        email: newUser.email,
        avatar: newUser.avatar,
        createdAt: newUser.createdAt
      }
    })
  } catch (error) {
    console.error('注册错误:', error)
    res.status(500).json({ 
      success: false,
      message: '注册失败'
    })
  }
})

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body
  
  if (!username || !password) {
    return res.status(400).json({ 
      success: false,
      message: '请提供用户名和密码'
    })
  }
  
  const user = users.find(u => u.username === username)
  
  if (user && bcrypt.compareSync(password, user.password)) {
    req.session.userId = user.id
    res.json({ 
      success: true,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        createdAt: user.createdAt
      }
    })
  } else {
    res.status(401).json({ 
      success: false,
      message: '用户名或密码错误'
    })
  }
})

// 获取用户信息
app.get('/api/profile', (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ 
      success: false,
      message: '未登录'
    })
  }
  
  const user = users.find(u => u.id === req.session.userId)
  if (user) {
    res.json({ 
      success: true,
      data: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        createdAt: user.createdAt
      }
    })
  } else {
    res.status(404).json({ 
      success: false,
      message: '用户不存在'
    })
  }
})

// 更新用户信息 (新增)
app.put('/api/profile', (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ 
      success: false,
      message: '未登录'
    })
  }
  
  const userIndex = users.findIndex(u => u.id === req.session.userId)
  if (userIndex === -1) {
    return res.status(404).json({ 
      success: false,
      message: '用户不存在'
    })
  }
  
  const { email, avatar } = req.body
  const updatedUser = { ...users[userIndex] }
  
  if (email) updatedUser.email = email
  if (avatar) updatedUser.avatar = avatar
  
  users[userIndex] = updatedUser
  
  res.json({ 
    success: true,
    data: {
      id: updatedUser.id,
      username: updatedUser.username,
      email: updatedUser.email,
      avatar: updatedUser.avatar,
      createdAt: updatedUser.createdAt
    }
  })
})

// 退出登录
app.post('/api/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      console.error('退出登录错误:', err)
      return res.status(500).json({ 
        success: false,
        message: '退出登录失败'
      })
    }
    res.clearCookie('connect.sid')
    res.json({ 
      success: true,
      message: '退出登录成功'
    })
  })
})

// 健康检查端点 (新增)
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'OK',
    timestamp: new Date().toISOString()
  })
})

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`)
})